package com.vca.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Base64;

/**
 *@Description:VCA——Lecole短信发送Util
 *@author:chenbing
 *@date 2023/3/3 15:43
 */
@Component
public class BasicAuthSmsUtils {

    public static final Logger logger = LoggerFactory.getLogger(BasicAuthSmsUtils.class);

    /**
     *@Description:请求路径API
     *@author:chenbing
     *@date 2023/3/3 15:40
     */
    @Value(value = "${vca.sms.apiUrl}")
    private String apiUrl;

    /**
     *@Description:用户名和密码
     *@author:chenbing
     *@date 2023/3/3 15:40
     */
    @Value(value = "${vca.sms.auth}")
    private String auth;


    final static String proxyHost = "zproxy-sh.cn.ali.rccad.net";
    final static Integer proxyPort = 80;

//    public static final String apiUrl = "https://api.quality.rcdc.richemont.cn/rwf-notification/api/v1/message";

//    public static final String auth = "lecolequser:Richemont1";

//    public static void main(String[] args) {
//        VcaMessageVo vcaMessageVo = new VcaMessageVo();
//        VcaMessageVo.Header header = new VcaMessageVo.Header();
//        header.setTo("15364268364");
//        header.setTemplateCode("lecole_reservation_notice");
//        vcaMessageVo.setHeader(header);
//        HashMap<String, String> contentMap = new HashMap<>();
//        contentMap.put("name","jackson");
//        vcaMessageVo.setContent(contentMap);
//        String jsonData = JSONObject.toJSONString(vcaMessageVo);
//        try {
//            send(jsonData);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    public void send(String jsonData, Boolean enable) throws IOException {
        //忽略SSL证书
        SslUtil.ignoreSsl();
        logger.info("jsonData======>{}",jsonData);
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        // 创建HttpURLConnection对象并设置请求头和请求体
        URL url = new URL(apiUrl);
        HttpURLConnection connection = null;
        if (enable){
            // Create a proxy object and configure the HttpURLConnection to use it
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = (HttpURLConnection) url.openConnection(proxy);
        }else {
            System.getProperties().clear();
            connection = (HttpURLConnection) url.openConnection();
        }


        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuth);
        connection.setRequestProperty("Content-Type", "application/json; utf-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        byte[] input = jsonData.getBytes("utf-8");
        outputStream.write(input, 0, input.length);
        outputStream.flush();

        // 发送HTTP请求并获取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            logger.info("BasicAuthSmsUtils response===>{}", response.toString());
        } else {
            logger.info("BasicAuthSmsUtils HTTP error code: " + responseCode);
        }
        connection.disconnect();
    }

    public static void main(String[] args) {
        String auth = "lecolequser:Richemont1";
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        System.out.println("encodedAuth = " + encodedAuth);
    }
}
